package com.validator;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;

import com.bean.User;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class IsUsernameExist_login extends FieldValidatorSupport {
	private boolean trim = true;
	private List<User> list; 
	private String MyfieldValue = null;
	private User user = new User();

	@Override
	public void validate(Object o) throws ValidationException {
		//1. 获取字段的名字和值
		String fieldName = getFieldName();
		MyfieldValue = (String) getFieldValue(fieldName, o);
		//2. 验证
		if (MyfieldValue == null)
			return;
		if (trim)
			MyfieldValue = MyfieldValue.trim();
		if (MyfieldValue.length() == 0) {
			return;
		}
		//判断用户名是否存在，若不存在，返回false
		//从数据库查询，返回结果集
		Configuration conf = new Configuration().configure();
		SessionFactory sessionFactory = conf.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		
		User user_current_login = new User();
		String username = MyfieldValue;
		System.out.println(MyfieldValue);
		user_current_login.setUsername(username);
		
		try{
			String hql = "from User u where u.username = :username";
			Query query = session.createQuery(hql);
			query.setParameter("username", user_current_login.getUsername());
			
			list = query.list();
			//判断结果集是否为null，若是rs为false，否rs为true
			if(list.isEmpty()) addFieldError(fieldName, o);
			
			transaction.commit();
			session.close();
			sessionFactory.close();
			
		}catch(Exception e){
			addFieldError(fieldName, o);
		}
	
	}

	public String getMyfieldValue() {
		return MyfieldValue;
	}

	public void setMyfieldValue(String myfieldValue) {
		MyfieldValue = myfieldValue;
	}

	public List<User> getList() {
		return list;
	}

	public void setList(List<User> list) {
		this.list = list;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	
	
	
	
	

}
